package persistencia;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.timetracker.TimeRecord;

public class TimeTrackerDatabaseHelper {
	public static final String DB_NAME = "timetracker.db";
	public static final int DB_VERSION = 3;

	public static final String TIMERECORD_TABLE_NAME= " timerecords ";
	public static final String TIMERECORD_COLUMN_ID= " _id ";
	public static final String TIMERECORD_COLUMN_TIME= " time ";
	public static final String TIMERECORD_COLUMN_NOTES= " notes ";

	private TimeTrackerOpenHelper openHelper;
	private SQLiteDatabase database;

	public TimeTrackerDatabaseHelper(Context context){
		openHelper = new TimeTrackerOpenHelper(context);
		database = openHelper.getWritableDatabase();
	}
	
	public void saveTimeRecord(TimeRecord timeRecord){
		String time = timeRecord.getTime();
		String notes = timeRecord.getNotes();
		
		ContentValues contentValues = new ContentValues();
		contentValues.put(TIMERECORD_COLUMN_TIME, time);
		contentValues.put(TIMERECORD_COLUMN_NOTES, notes);
		
		database.insert(TIMERECORD_TABLE_NAME, null, contentValues);
	}
	
//	public  getAllTimeRecords(){
//		
//	}
	
	public ArrayList<TimeRecord> getTimeRecordList(){
		ArrayList<TimeRecord> listTimeRecord = new ArrayList<TimeRecord>();
		
		Cursor cursor = database.query(TIMERECORD_TABLE_NAME, null, null, null, null, null, TIMERECORD_COLUMN_ID);
		
		if (cursor.moveToFirst()){
			do {
				String time = cursor.getString(1);
				String notes = cursor.getString(2);

				TimeRecord timeRecord = new TimeRecord(time, notes);
				
				listTimeRecord.add(timeRecord);
				
				Log.i("DB Row", timeRecord.toString());
				
			} while (cursor.moveToNext());
		}
		
		if (!cursor.isClosed()){
			cursor.close();
		}
		
		return listTimeRecord;
	}



	private class TimeTrackerOpenHelper extends SQLiteOpenHelper {

		public static final String TIMERECORD_CREATE_TABLE = "CREATE TABLE "+TIMERECORD_TABLE_NAME+
				"("+TIMERECORD_COLUMN_ID+ " INTEGER PRIMARY KEY, "+TIMERECORD_COLUMN_TIME+" TEXT, "+
				TIMERECORD_COLUMN_NOTES+" TEXT);";



		public static final String DROP_TABLE = " DROP TABLE IF EXISTS ";

		public TimeTrackerOpenHelper(Context context){
			super(context, DB_NAME, null, DB_VERSION);	
		}

		@Override
		public void onCreate(SQLiteDatabase database) {
			database.execSQL(TIMERECORD_CREATE_TABLE);
			Log.w("TIMETRACKER_DB ", "TIMETRACKER_DB foi criado com sucesso");

		}

		@Override
		public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
			database.execSQL(DROP_TABLE + TIMERECORD_TABLE_NAME);
			onCreate(database);
		}

	}


}